<?php
class SponsorField extends TextField {
	private static $allowed_actions = array(
        'check_sponsor'
    );
	
	/**
     * The url to use as the check sponsor
     * @var string
     */
    protected $checkSponsorURL;
	
	/**
	 * @var UsernameField
	 */
	protected $usernameField = null;
	
	/**
	 * @var NameField
	 */
	protected $nameField = null;
	
	/**
	 * @var IDField
	 */
	protected $idField = null;
	
	public function __construct($name, $title = null, $value = ""){
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
		Requirements::javascript(FRAMEWORK_DIR . '/javascript/i18n.js');
		Requirements::add_i18n_javascript('network/javascript/lang');
        Requirements::javascript('network/javascript/SponsorField.min.js');
		Requirements::css('network/css/SponsorField.css');
		
		$this->usernameField = TextField::create($name . '[username]', false);
		$this->nameField = TextField::create($name . '[name]', false);
		$this->idField = HiddenField::create($name . '[id]');

		parent::__construct($name, $title, $value);
	}
	
	function Field($properties = array()) {
		$this->usernameField->setAttribute('rel', 'sponsor-username');
		$this->usernameField->setAttribute('data-url', $this->getCheckSponsorURL());
		$this->usernameField->setAttribute('autocomplete', 'off');
		if ($this->Required()) {
			$this->usernameField->setAttribute('required', 'required');
			$this->usernameField->setAttribute('aria-required', 'true');
		}
		$this->nameField->setAttribute('rel', 'sponsor-name');
		$this->nameField->setAttribute('readonly', 'readonly');
		$this->nameField->setAttribute('autocomplete', 'off');
		$this->nameField->setAttribute('tabindex', '-1');
		$this->idField->setAttribute('rel', 'sponsor-id');
		$this->idField->setAttribute('autocomplete', 'off');
        return sprintf('%s %s %s', $this->usernameField->Field(), $this->nameField->Field(), $this->idField->Field());
    }
	
	function Type() {
		return 'sponsor text';
	}
	
	/**
	 * Set the field value.
	 * 
	 * @param mixed $value
	 * @return FormField Self reference
	 */
	public function setValue($value) {
		if(is_array($value)) {
			$this->value = $value['username'];
		} else {
			$this->value = $value;
		}
		
		$this->usernameField->setValue($this->value);
		if($member = Distributor::get_obj_by_username($this->value)){
			$this->nameField->setValue($member->getName());
			$this->idField->setValue($member->ID);
		}
		else{
			$this->nameField->setValue('');
			$this->idField->setValue('');
		}

		return $this;
	}
	
	public function setDisabled($bool) {
		parent::setDisabled($bool);
		$this->usernameField->setDisabled($bool);
		$this->nameField->setDisabled($bool);
		return $this;
	}

	public function setReadonly($bool) {
		parent::setReadonly($bool);
		$this->usernameField->setReadonly($bool);
		return $this;
	}
	
	/**
	 * Method to save this form field into the given data object.
	 * By default, makes use of $this->dataValue()
	 * 
	 * @param DataObjectInterface $record DataObject to save data into
	 */
	public function saveInto(DataObjectInterface $record) {
		$var = $this->dataValue();
		$record->setCastedField($this->getName(), $var);
		$record->setCastedField('SetSponsorUsername', $var);
	}
	
	/**
	 * Makes a read only field
	 *
	 * @return ReadonlyField
	 */
	public function performReadonlyTransformation() {
		$copy = $this->castedCopy('SponsorField_Readonly');
		$copy->setReadonly(true);
		$copy->usernameField = $this->usernameField->performReadonlyTransformation();
		$copy->usernameField->setReadonly(true);
		$copy->nameField = $this->nameField->performReadonlyTransformation();
		$copy->nameField->setReadonly(true);
		$copy->idField = $this->idField->performReadonlyTransformation();
		$copy->idField->setReadonly(true);
		return $copy;
	}
	
	/**
     * Set the URL used to check sponsor.
     * 
     * @param string $URL The URL used for check sponsor.
     */
    public function setCheckSponsorURL($URL) {
        $this->checkSponsorURL = $url;
		return $this;
    }
	
	/**
     * Get the URL used to check sponsor. Returns null
     * if the built-in mechanism is used.
     *  
     * @return The URL used for check sponsor.
     */
    public function getCheckSponsorURL() {

        if (!empty($this->checkSponsorURL))
            return $this->checkSponsorURL;

        // Attempt to link back to itself
        return $this->Link('check_sponsor');
    }
	
    function validate($validator) {
        $sponsor = Sponsor::get()->filter('Member.Username', $this->Value())->first();

        if(!$sponsor) {
            $validator->validationError($this->name, _t('SponsorField.SPONSOR_USERNAME_INVALID', "The sponsor username is invalid"));
            return false;
        }

        return true;
    }
	
	/**
     * Handle a request for an sponsor checking.
     * 
     * @param HTTPRequest $request The request to handle.
     * @return Sponsor data result
     */
    function check_sponsor(HTTPRequest $request) {
    	$data = array('result' => 'error', 'id' => '', 'name' => '', 'msg' => _t('SponsorField.SPONSOR_USERNAME_INVALID', "The sponsor username is invalid"));
		$sponsor = Sponsor::get()->filter('Member.Username', $request->getVar('username'))->first();
		if($sponsor){
			if($placement = Placement::get()->filter('Member.Username', $request->getVar('placement'))->first()){
				$obj = Placement::get()->filter('Member.Username', $request->getVar('username'))->first();
				$checkPlacement = Placement::get()
	        	->filter('NLeft:GreaterThanOrEqual', (int)$obj->NLeft)
	        	->filter('NRight:LessThanOrEqual', (int)$obj->NRight)
				->filter('MemberID', (int)$placement->MemberID)->count();
				if($checkPlacement){
					$data = array('result' => 'success', 'id' => $sponsor->Member()->ID, 'name' => $sponsor->Member()->getName(), 'msg' => _t('SponsorField.SPONSOR_USERNAME_VALID', "The sponsor username is valid"));
				}
			}
			else{
				$data = array('result' => 'success', 'id' => $sponsor->Member()->ID, 'name' => $sponsor->Member()->getName(), 'msg' => _t('SponsorField.SPONSOR_USERNAME_VALID', "The sponsor username is valid"));
			}
		}
        // the response body
        return Convert::array2json($data);
    }
}

/**
 * Readonly version of {@link SponsorField}.
 * Allows sponsor info to be represented in a form, by showing in a user friendly format.
 * @package network
 * @subpackage sponsor-field
 */
class SponsorField_Readonly extends SponsorField {
	/**
	 * Include a hidden field in the HTML for the readonly field
	 * @var boolean
	 */
	protected $includeHiddenField = false;

	/**
	 * If true, a hidden field will be included in the HTML for the readonly field.
	 * 
	 * This can be useful if you need to pass the data through on the form submission, as
	 * long as it's okay than an attacker could change the data before it's submitted.
	 *
	 * This is disabled by default as it can introduce security holes if the data is not
	 * allowed to be modified by the user.
	 * 
	 * @param boolean $includeHiddenField
	 */
	public function setIncludeHiddenField($includeHiddenField) {
		$this->includeHiddenField = $includeHiddenField;
	}
	
	public function Field($properties = array()) {
		$value = $this->dataValue();
		$text = sprintf('%s - %s', $value, $this->nameField->dataValue());
		$copy = $this->castedCopy('ReadonlyField')->setReadonly(true)->setTitle($this->title)->setValue($text);
		// Include a hidden field in the HTML
		if($this->includeHiddenField && $this->readonly) {
			return $copy->Field($properties) . $this->usernameField->performReadonlyTransformation()->setReadonly(false)->Field($properties) . $this->nameField->performReadonlyTransformation()->setReadonly(false)->Field($properties) . $this->idField->performReadonlyTransformation()->setReadonly(false)->Field($properties);
		} else {
			return $copy->Field($properties);
		}
	}
}
?>
